<template>
  <div class="article-detail">
    <el-container>
      <el-header>
        <div class="header-content">
          <div class="header-left">
            <el-button type="primary" @click="router.push('/knowledge')">
              <el-icon><ArrowLeft /></el-icon>
              返回列表
            </el-button>
          </div>
          <div class="header-right">
            <h2>文章详情</h2>
          </div>
        </div>
      </el-header>
      <el-main>
        <div class="content-container">
          <!-- 文章内容 -->
          <el-card class="article-card">
            <template #header>
              <div class="article-header">
                <h1 class="article-title">{{ article.name }}</h1>
                <div class="article-meta">
                  <span class="publish-time">发布时间：{{ formatDate(article.createdAt) }}</span>
                </div>
              </div>
            </template>
            <div class="article-content">
              <div class="article-image" v-if="article.imageUrl">
                <img :src="article.imageUrl" :alt="article.name">
              </div>
              <div class="article-text">{{ article.description }}</div>
            </div>
          </el-card>

          <!-- 评论区 -->
          <div class="comments-section">
            <h3>评论区</h3>
            
            <!-- 发表评论 -->
            <div class="comment-form" v-if="userStore.isLoggedIn">
              <el-input
                v-model="commentForm.content"
                type="textarea"
                :rows="3"
                placeholder="写下你的评论..."
              />
              <el-button type="primary" @click="submitComment" :loading="submitting">
                发表评论
              </el-button>
            </div>
            <div v-else class="login-tip">
              <el-link type="primary" @click="showLoginDialog">登录后发表评论</el-link>
            </div>

            <!-- 评论列表 -->
            <div class="comments-list">
              <el-card v-for="comment in comments" :key="comment.commentId" class="comment-card">
                <div class="comment-header">
                  <div class="user-info">
                    <el-avatar :size="40" :src="comment.imageUrl" />
                    <div class="user-meta">
                      <span class="user-name">{{ comment.callName || comment.userName }}</span>
                      <span class="comment-time">{{ formatDate(comment.createdAt) }}</span>
                    </div>
                  </div>
                  <div class="comment-actions">
                    <el-button 
                      type="link" 
                      size="small" 
                      @click="showReplyForm(comment)"
                    >
                      回复
                    </el-button>
                    <el-button 
                      type="link" 
                      size="small" 
                      @click="handleDeleteComment(comment.commentId)"
                      v-if="canDelete(comment)"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
                <div class="comment-content">
                  <p>{{ comment.content }}</p>
                </div>

                <!-- 回复列表 -->
                <div class="replies-list" v-if="comment.replies && comment.replies.length > 0">
                  <div v-for="reply in comment.replies" :key="reply.replyId" class="reply-item">
                    <div class="reply-header">
                      <div class="user-info">
                        <el-avatar :size="32" :src="reply.imageUrl" />
                        <div class="user-meta">
                          <span class="user-name">{{ reply.callName || reply.userName }}</span>
                          <span class="reply-time">{{ formatDate(reply.createdAt) }}</span>
                        </div>
                      </div>
                      <el-button 
                        type="link" 
                        size="small" 
                        @click="handleDeleteReply(reply.replyId)"
                        v-if="canDelete(reply)"
                      >
                        删除
                      </el-button>
                    </div>
                    <p class="reply-content">{{ reply.content }}</p>
                  </div>
                </div>
                
                <!-- 回复表单 -->
                <div class="reply-form" v-if="activeReplyId === comment.commentId">
                  <el-input
                    v-model="replyForm.content"
                    type="textarea"
                    :rows="2"
                    placeholder="写下你的回复..."
                  />
                  <div class="reply-actions">
                    <el-button @click="cancelReply">取消</el-button>
                    <el-button type="primary" @click="submitReply(comment.commentId)" :loading="submitting">
                      提交回复
                    </el-button>
                  </div>
                </div>
              </el-card>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { 
  getArticleDetail, 
  getArticleComments, 
  getCommentReplies,
  addArticleComment,
  addCommentReply,
  deleteComment,
  deleteReply
} from '@/api/plants'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 状态变量
const article = ref({})
const comments = ref([])
const submitting = ref(false)
const activeReplyId = ref(null)

// 评论表单
const commentForm = reactive({
  content: ''
})

// 回复表单
const replyForm = reactive({
  content: ''
})

// 加载文章详情
const loadArticle = async () => {
  console.log('开始加载文章详情，文章ID:', route.params.id)
  try {
    const response = await getArticleDetail(route.params.id)
    console.log('获取文章详情响应:', response)
    
    if (Array.isArray(response)) {
      if (response.length > 0) {
        console.log('文章详情数据(数组):', response[0])
        article.value = response[0]
      } else {
        console.error('文章不存在')
        ElMessage.error('文章不存在')
        router.push('/knowledge')
      }
    } else if (response?.data) {
      console.log('文章详情数据(对象):', response.data)
      article.value = response.data
    } else if (response && Object.keys(response).length > 0) {
      // 直接返回的对象
      console.log('文章详情数据(直接对象):', response)
      article.value = response
    } else {
      console.error('加载文章详情失败，响应数据无效:', response)
      ElMessage.error('获取文章详情失败')
      router.push('/knowledge')
    }
  } catch (error) {
    console.error('加载文章详情出错，详细错误:', error)
    ElMessage.error(error?.response?.data?.message || '获取文章详情失败')
    router.push('/knowledge')
  }
}

// 加载评论列表
const loadComments = async () => {
  console.log('开始加载评论列表，文章ID:', route.params.id)
  try {
    const response = await getArticleComments(route.params.id)
    console.log('获取评论列表响应:', response)
    
    if (Array.isArray(response)) {
      console.log('评论列表数据(数组):', response)
      comments.value = response || []
    } else if (response?.data) {
      console.log('评论列表数据(对象):', response.data)
      comments.value = Array.isArray(response.data) ? response.data : []
    } else if (response && typeof response === 'object') {
      console.log('评论列表数据(直接对象):', response)
      comments.value = [response]
    } else {
      console.warn('暂无评论')
      comments.value = []
      return
    }

    // 加载每条评论的回复
    if (comments.value.length > 0) {
      console.log('开始加载评论回复...')
      for (const comment of comments.value) {
        if (!comment.commentId) {
          console.warn('评论缺少commentId:', comment)
          continue
        }
        
        console.log('加载评论ID的回复:', comment.commentId)
        try {
          const repliesResponse = await getCommentReplies(comment.commentId)
          console.log('获取回复列表响应:', repliesResponse)
          
          if (Array.isArray(repliesResponse)) {
            console.log('回复数据(数组):', repliesResponse)
            comment.replies = repliesResponse
          } else if (repliesResponse?.data) {
            console.log('回复数据(对象):', repliesResponse.data)
            comment.replies = Array.isArray(repliesResponse.data) ? repliesResponse.data : []
          } else {
            console.warn('无回复数据')
            comment.replies = []
          }
        } catch (error) {
          console.error('加载评论回复失败:', error)
          comment.replies = []
        }
      }
    } else {
      console.log('没有评论，跳过加载回复')
    }
  } catch (error) {
    console.error('加载评论列表出错，详细错误:', error)
    ElMessage.error(error?.response?.data?.message || '获取评论列表失败')
    comments.value = []
  }
}

// 提交评论
const submitComment = async () => {
  if (!commentForm.content.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }

  submitting.value = true
  try {
    const response = await addArticleComment(route.params.id, {
      content: commentForm.content,
      userId: userStore.userInfo.userId
    })
    console.log('提交评论响应:', response)

    if (response?.code === 200 || response?.success === true) {
      ElMessage.success(response.message || response.msg || '评论发表成功')
      commentForm.content = ''
      loadComments()
    } else {
      console.error('评论发表失败，响应:', response)
      ElMessage.error(response?.message || response?.msg || '评论发表失败')
    }
  } catch (error) {
    console.error('评论发表失败，错误:', error)
    ElMessage.error(error?.response?.data?.message || '评论发表失败')
  } finally {
    submitting.value = false
  }
}

// 显示回复表单
const showReplyForm = (comment) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    return
  }
  activeReplyId.value = comment.commentId
  replyForm.content = ''
}

// 取消回复
const cancelReply = () => {
  activeReplyId.value = null
  replyForm.content = ''
}

// 提交回复
const submitReply = async (commentId) => {
  if (!replyForm.content.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }

  submitting.value = true
  try {
    const response = await addCommentReply(commentId, {
      content: replyForm.content,
      userId: userStore.userInfo.userId
    })
    console.log('提交回复响应:', response)

    if (response?.code === 200 || response?.success === true) {
      ElMessage.success(response.message || response.msg || '回复发表成功')
      cancelReply()
      loadComments()
    } else {
      console.error('回复发表失败，响应:', response)
      ElMessage.error(response?.message || response?.msg || '回复发表失败')
    }
  } catch (error) {
    console.error('回复发表失败，错误:', error)
    ElMessage.error(error?.response?.data?.message || '回复发表失败')
  } finally {
    submitting.value = false
  }
}

// 确认删除评论
const handleDeleteComment = (commentId) => {
  console.log('准备删除评论，commentId:', commentId)
  ElMessageBox.confirm('确定要删除这条评论吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      console.log('开始发送删除评论请求，commentId:', commentId)
      const response = await deleteComment(commentId)
      console.log('删除评论响应:', response)
      
      if (response?.code === 200 || response?.success === true) {
        ElMessage.success(response.message || response.msg || '删除成功')
        loadComments()
      } else {
        console.error('删除评论失败，响应:', response)
        ElMessage.error(response?.message || response?.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除评论失败:', error)
      ElMessage.error(error?.response?.data?.message || '删除评论失败')
    }
  }).catch(() => {
    console.log('用户取消删除评论')
  })
}

// 删除回复
const handleDeleteReply = async (replyId) => {
  console.log('准备删除回复，replyId:', replyId)
  try {
    ElMessageBox.confirm('确定要删除这条回复吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      console.log('开始发送删除回复请求，replyId:', replyId)
      const response = await deleteReply(replyId)
      console.log('删除回复响应:', response)
      
      if (response?.code === 200 || response?.success === true) {
        ElMessage.success(response.message || response.msg || '删除成功')
        loadComments()
      } else {
        console.error('删除回复失败，响应:', response)
        ElMessage.error(response?.message || response?.msg || '删除失败')
      }
    }).catch(() => {
      console.log('用户取消删除回复')
    })
  } catch (error) {
    console.error('删除回复失败:', error)
    ElMessage.error(error?.response?.data?.message || '删除回复失败')
  }
}

// 检查是否可以删除评论或回复
const canDelete = (item) => {
  return userStore.isLoggedIn && item.userId === userStore.userInfo.userId
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 显示登录对话框
const showLoginDialog = () => {
  // 这里需要实现显示登录对话框的逻辑
  ElMessage.warning('请先登录')
}

onMounted(() => {
  loadArticle()
  loadComments()
})
</script>

<style scoped>
.article-detail {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.content-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.article-card {
  margin-bottom: 30px;
}

.article-header {
  padding: 20px 0;
}

.article-title {
  margin: 0 0 16px 0;
  font-size: 28px;
  color: #333;
}

.article-meta {
  color: #999;
  font-size: 14px;
}

.article-content {
  padding: 20px 0;
}

.article-image {
  margin-bottom: 20px;
  text-align: center;
}

.article-image img {
  max-width: 100%;
  border-radius: 8px;
}

.article-text {
  font-size: 16px;
  line-height: 1.8;
  color: #333;
  white-space: pre-wrap;
}

.comments-section {
  margin-top: 40px;
}

.comments-section h3 {
  margin-bottom: 20px;
  font-size: 20px;
  color: #333;
}

.comment-form {
  margin-bottom: 30px;
}

.comment-form .el-button {
  margin-top: 10px;
}

.login-tip {
  text-align: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
  margin-bottom: 20px;
}

.comment-card {
  margin-bottom: 20px;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-meta {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.user-name {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.comment-time, .reply-time {
  color: #999;
  font-size: 12px;
}

.comment-content {
  margin-bottom: 16px;
}

.comment-content p {
  margin: 0;
  font-size: 14px;
  line-height: 1.6;
  color: #333;
}

.reply-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.reply-content {
  margin: 0;
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  padding-left: 44px;
}

.replies-list {
  margin-top: 16px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.reply-item {
  margin-bottom: 16px;
  &:last-child {
    margin-bottom: 0;
  }
}

.reply-form {
  margin-top: 16px;
}

.reply-actions {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style> 